import { ReactText, useEffect } from 'react';
import React, { useState } from 'react';
import { Button, Progress, Tag, Space, Avatar, Timeline, Modal, message } from 'antd';
import ProList from '@ant-design/pro-list';
import { request, Access, useAccess } from 'umi';
import ProCard from '@ant-design/pro-card';
import { api } from '@/global';
import InsertFile from '../InsertFile';
import FileAvatar from '@/util/GenearyFileAvatar';

import dayjs from 'dayjs';
import PDFRender from '@/components/PDFRender';
import DOCXRender from '@/components/DOCXRender';
import ImageRender from '@/components/ImageRender';
type FileType = {
  id: number;
  title: string;
  fileName: string;
  fileSuffix: string;
  createTime: string;
  fileDescribe: string;
  pathName: string;
  pathCode: string;
  bucketCode: string;
  bucketName: string;
  fileOssPath: string;
  name: string;
};

type propsType = {
  selectFolder: string;
  selectBucket: string;
};

type paramsType = {
  FileSuffix: string;
  pageSize: number;
  current: number;
  fileOwnUserName: string;
  filename: string;
};

export default (props: propsType) => {
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>([]);
  const [fileData, GetFileData] = useState<FileType[]>();
  const [isible, SetIsible] = useState(false);
  const [deleteFile, SetDeleteFile] = useState<FileType>();
  const access = useAccess();
  const getAllFileInfo = async (params: paramsType) => {
    const result = await request(api.getAllFileInfo, {
      params: {
        pathCode: props.selectFolder ? props.selectFolder : '',
        bucketName: props.selectBucket ? props.selectBucket : '',
        ...params,
      },
    });
    GetFileData(result.data);
  };
  useEffect(() => {
    getAllFileInfo();
  }, [props]);

  const deletFile = async (id: string) => {
    const result = await request(api.deleteFile, {
      method: 'POST',
      data: {
        id,
      },
    });

    if (result.success) {
      message.info('删除成功');
      getAllFileInfo();
    }

    SetIsible(false);
  };

  const downloadFile = (data, fileName) => {
    if (!data) {
      return;
    }
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', fileName + '.pdf');
    document.body.appendChild(link);
    link.click();
  };

  return (
    <ProCard
      title="文件列表"
      tooltip="点击左侧文件夹查看文件下对应的文件"
      headerBordered
      key={'upload'}
      extra={[<InsertFile key="inserFile" getAllFileInfo={getAllFileInfo} />]}
    >
      <Access key="uploadfileList" accessible={access.normalButtonFilter('FILE_UPLOAD:SELECT')}>
        <ProList<FileType>
          rowKey="title"
          expandable={{ expandedRowKeys, onExpandedRowsChange: setExpandedRowKeys }}
          dataSource={fileData}
          search={{
            filterType: 'light',
          }}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
          }}
          request={(params: paramsType) => {
            getAllFileInfo(params);
          }}
          metas={{
            title: {
              render: (_, info) => {
                return <div style={{ minWidth: '400px' }}>{info.title}</div>;
              },
              dataIndex: 'filename',
              title: '文件名',
            },
            subTitle: {
              render: (_, info) => {
                return (
                  <Space size={0}>
                    <Tag color="blue" key={info.name}>
                      {info.name}
                    </Tag>
                    <Tag color="blue">{dayjs(info.createTime).format('YYYY-MM-DD')}</Tag>
                  </Space>
                );
              },
              search: false,
            },
            description: {
              render: (_, info) => {
                return <div style={{ minWidth: '400px' }}>{info.fileDescribe}</div>;
              },
              search: false,
            },
            avatar: {
              render: (_, info) => {
                return <Avatar shape="square" src={FileAvatar(info.fileSuffix)}></Avatar>;
              },
              search: false,
            },
            content: {
              search: false,
            },
            fileOwnUserName: {
              // 自己扩展的字段，主要用于筛选，不在列表中显示
              title: '文件负责人姓名',
              valueType: 'select',
              request: async () => {
                const list: any[] = [];
                const result = await request(api.getSimpleUserInfo);
                list.push({ label: '全部', value: '' });
                result.data.forEach((item) => {
                  list.push({ label: item.name, value: item.id });
                });

                return list;
              },
            },
            FileSuffix: {
              title: '文件类型',
              valueType: 'select',
              valueEnum: {
                all: { text: '全部', status: 'Default' },
                open: {
                  text: '未解决',
                  status: 'Error',
                },
                closed: {
                  text: '已解决',
                  status: 'Success',
                },
                processing: {
                  text: '解决中',
                  status: 'Processing',
                },
              },
              request: async () => {
                const d = await request(api.getFileSuffix);
                const list: any[string] = [];
                list.push({ label: '全部', value: '' });
                d.data.forEach((item: string) => {
                  list.push({ label: item, value: item });
                });

                return list;
              },
            },

            actions: {
              search: false,
              render: (_, info) => {
                return [
                  info.fileSuffix === 'pdf' && (
                    <Access key={info.id} accessible={access.normalButtonFilter('FILE:VIEW')}>
                      <PDFRender key={info.id} url={info.fileOssPath} title="预览" />
                    </Access>
                  ),
                  info.fileSuffix === 'docx' && (
                    <Access key={info.id} accessible={access.normalButtonFilter('FILE:VIEW')}>
                      <DOCXRender key={info.id} url={info.fileOssPath} title="预览" />
                    </Access>
                  ),
                  (info.fileSuffix === 'png' ||
                    info.fileSuffix === 'jpg' ||
                    info.fileSuffix === 'jpeg') && (
                    <Access key={info.id} accessible={access.normalButtonFilter('FILE:VIEW')}>
                      <ImageRender key={info.id} title="预览" url={info.fileOssPath} />
                    </Access>
                  ),
                  <Access
                    key={'download' + info.id}
                    accessible={access.normalButtonFilter('FILE:DOWNLOAD')}
                  >
                    <a
                      key={info.fileDescribe + info.createTime + info.id}
                      onClick={() => {
                        request(api.addFileDownload, {
                          params: {
                            id: info.id,
                          },
                        });

                        if (info.fileSuffix === 'pdf') {
                          downloadFile(info.fileOssPath, info.fileName);
                        } else {
                          window.open(info.fileOssPath);
                        }
                      }}
                    >
                      下载
                    </a>
                  </Access>,
                  <Access
                    key={'delete' + info.id}
                    accessible={access.normalButtonFilter('FILE_UPLOAD:DELETE')}
                  >
                    <a
                      key={info.fileOssPath}
                      onClick={() => {
                        SetIsible(true);
                        SetDeleteFile(info);
                      }}
                    >
                      删除
                    </a>
                  </Access>,
                ];
              },
            },
          }}
        />
      </Access>
      <Modal
        title="是否删除文件夹"
        visible={isible}
        onOk={() => {
          if (deleteFile?.id) {
            deletFile(deleteFile?.id);
          }
        }}
        onCancel={() => {
          SetIsible(false);
        }}
      >
        是否删除&nbsp;&nbsp;
        <span style={{ fontWeight: 900, fontSize: 25, color: '#3498db' }}>{deleteFile?.title}</span>
        &nbsp;&nbsp;用户
      </Modal>
    </ProCard>
  );
};
